package cn.xiaobai.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.core.io.ClassPathResource;

import java.io.*;
import java.util.Objects;

/**
 * @Author yangdaji
 * @Date 2022/10/12 0012
 * @PackageName cn.xiaobai.utils
 * @ClassName ConfigReadUtils
 */
@Slf4j
public class ConfigReadUtils {

    /**
     * 读取热键配置
     *
     * @param filename 文件名称
     * @return
     * @throws IOException
     */
    public static String readConfigFile(String filename) {

        ApplicationHome applicationHome = new ApplicationHome();
        File source = applicationHome.getSource();
        InputStream fileInputStream = null;
        //判断是否是jar包
        if (Objects.isNull(source)) {
            log.info("[非jar包]-配置路径: {}", filename);
            try {
                fileInputStream = new ClassPathResource(filename).getInputStream();
            } catch (IOException e) {
               log.error("[非jar包]-文件流异常: {}",e.getMessage());
            }
        } else {
            String jarPath = source.getPath();
            if (jarPath.endsWith(".jar")) {
                File path = new File(jarPath);
                jarPath = path.getParent() + filename;
                log.info("[jar包]-配置路径: {}", jarPath);
            }
            try {
                fileInputStream = new FileInputStream(jarPath);
            } catch (FileNotFoundException e) {
                log.error("文件流异常: {}",e.getMessage());
            }
        }
        return fileRead(fileInputStream);

    }


    /**
     * 编译文件读取
     *
     * @param inputStream 输入流
     * @return
     */
    public static String fileRead(InputStream inputStream) {
        try (Reader reader = new InputStreamReader(inputStream);
             BufferedReader br = new BufferedReader(reader)) {
            StringBuilder stringBuffer = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                stringBuffer.append(line);
                stringBuffer.append("\n");
            }
            String jsonStr = stringBuffer.toString().trim();
            if (jsonStr.startsWith("{") && jsonStr.endsWith("}")) {
                return jsonStr;
            }
            return null;
        } catch (Exception e) {
            log.error("文件读取出错: {}", e.getMessage());
            return null;
        }
    }

}
